package com.mys2sh.cookie;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mys2sh.model.User;

public abstract class UserCookie {
	public static void setLoginCookie(User user, HttpServletResponse response) {
		Cookie cooUid = new Cookie("uid", CookieCryptor.encode(user.getUid()));
		cooUid.setMaxAge(-1);
		cooUid.setPath("/mys2sh");
		cooUid.setDomain("ECshop.com");
		response.addCookie(cooUid);

		Cookie coouserName = new Cookie("uname", CookieCryptor.encode(user
				.getUserName()));
		coouserName.setMaxAge(-1);
		coouserName.setPath("/mys2sh");
		coouserName.setDomain("ECshop.com");
		response.addCookie(coouserName);

		if (!user.getNickName().equals("")) {
			Cookie cooNickName = new Cookie("nname", CookieCryptor.encode(user
					.getNickName()));
			cooNickName.setMaxAge(-1);
			cooNickName.setPath("/mys2sh");
			cooNickName.setDomain("ECshop.com");
			response.addCookie(cooNickName);
		}

		if (!user.getMobilePhone().equals("")) {
			Cookie cooMphone = new Cookie("mphone", CookieCryptor.encode(user
					.getMobilePhone()));
			cooMphone.setMaxAge(-1);
			cooMphone.setPath("/mys2sh");
			cooMphone.setDomain("ECshop.com");
			response.addCookie(cooMphone);
		}

		if (!user.getQq().equals("")) {
			Cookie cooQq = new Cookie("qq", CookieCryptor.encode(user.getQq()));
			cooQq.setMaxAge(-1);
			cooQq.setPath("/mys2sh");
			cooQq.setDomain("ECshop.com");
			response.addCookie(cooQq);
		}
	}

	public static void initCurrentCookie(HttpServletRequest request) {
		User user = new User();
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			int length = cookies.length;
			for (int i = 0; i < length; i++) {
				Cookie cookie = cookies[i];
				String cookieName = cookie.getName();
				if (cookieName.equals("uid")) {
					user.setUid(CookieCryptor.decode(cookie.getValue()));
				} else if (cookieName.equals("uname")) {
					user.setUserName(CookieCryptor.decode(cookie.getValue()));
				} else if (cookieName.equals("nname")) {
					user.setNickName(CookieCryptor.decode(cookie.getValue()));
				} else if (cookieName.equals("mphone")) {
					user
							.setMobilePhone(CookieCryptor.decode(cookie
									.getValue()));
				} else if (cookieName.equals("qq")) {
					user.setQq(CookieCryptor.decode(cookie.getValue()));
				}
			}
		}

		request.setAttribute("currentUser", user);
	}
}
